<template>
    <!-- 登录内容 -->
    <el-row class="login-container" justify="center" :align="'middle'">

        <!-- 卡片 -->
        <el-card style="max-width: 480px">
            <!-- 头部插槽 -->
            <template #header>
                <div class="card-header">
                    <img :src="imgUrl" alt="">
                </div>
            </template>
            <!-- 跳转 -->
            <div class="jump-link">
                <el-link type="primary" @click="handleChange">{{ formType ? '返回登录' : '注册账号' }}</el-link>
            </div>
            <!-- form表单 -->
            <el-form :model="loginForm" style="max-width: 600px;" class="demo-ruleForm" :rules="rules"
                ref="loginFormRef">
                <el-form-item prop="userName">
                    <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="UserFilled" />
                </el-form-item>
                <el-form-item prop="passWord">
                    <el-input v-model="loginForm.passWord" type="password" placeholder="密码" :prefix-icon="Lock" />
                </el-form-item>
                <!-- 验证码 -->
                <el-form-item prop="validCode" v-if="formType">
                    <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock" type="password">
                        <template #append>
                            <span @click="countDownChange">{{ countDown.validText }}</span>
                        </template>
                    </el-input>

                </el-form-item>

                <el-form-item>
                    <el-button type="primary" :style="{ width: '100%' }" @click="submitForm(loginFormRef)">
                        {{ formType ? '注册帐号' : '登录' }}
                    </el-button>
                </el-form-item>


            </el-form>
        </el-card>
    </el-row>
</template>
<script setup>
import { ref, reactive,computed,toRaw } from 'vue';
// 获取图片
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href
// 引入api
import { getCode, userAuthentication, login, menuPermissions } from '../../api';
// 引入组件库
import { UserFilled, Lock } from '@element-plus/icons-vue';
// 引入router
import { useRouter } from 'vue-router';
import { useStore } from 'Vuex';
// 切换表单 0 登录 1 注册
const formType = ref(0);
const handleChange = () => {
    formType.value = formType.value ? 0 : 1;
}
// 表单数据
const loginForm = reactive({
    userName: '',
    passWord: '',
    validCode: ''
});


const validateUser = (rule, value, callback) => {
    if (value === '') {
        callback(new Error(`请输入账号`))
    } else {
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        phoneReg.test(value) ? callback() : callback(new Error('手机号格式不对，请输入正确手机号'))
    }
}
//密码校验
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error(`请输入密码`))
    } else {
        const reg = /^[a-zA-Z0-9_-]{4,16}$/
        reg.test(value) ? callback() : callback(new Error('密码格式不对，需要4到16位字符，请确认格式'))
    }
}
// 表单校验
const rules = reactive({
    userName: [{ validator: validateUser, trigger: 'blur' }],
    passWord: [{ validator: validatePass, trigger: 'blur' }]

})

// 验证码
const countDown = reactive({
    validText: '获取验证码',
    validTime: 60
})
// 记录定时器状态
let flag = false;
// 验证码点击事件 60s倒计时
const countDownChange = () => {
    // 防止重复点击
    if (flag) return;
    // 校验手机号
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

    if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
        return ElMessage({ message: '请检查手机号是否正确', type: 'warning' });
    }

    // 倒计时
    const timer = setInterval(() => {
        // 倒计时结束
        if (countDown.validTime <= 0) {
            countDown.validText = '获取验证码';
            countDown.validTime = 60;
            flag = false;
            // 清除定时器 结束 定时器 重复倒计时清除
            clearInterval(timer);
        } else {
            // 防止重复点击
            // 60s 倒计时
            countDown.validTime--;
            // 倒计时显示
            countDown.validText = `${countDown.validTime}s`
        }


    }, 1000)
    flag = true;
    getCode({ tel: loginForm.userName }).then(({ data }) => {
        console.log(data, "data");
        if (data.code === 10000) {
            ElMessage.success("发送成功");
        }
    });
}

// 表单验证规则
const loginFormRef = ref();
const router = useRouter();
const store = useStore();
// 获取菜单权限
const routerList = computed(()=>store.state.menu.routerList)
// 登录  注册 提交
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        console.log("=================");
        if (!valid) {
            console.log('error submit!', fields)
        }
        // 判断登录注册
        if (formType.value) {
            // 注册
            userAuthentication(loginForm).then(({ data }) => {
                if (data.code === 10000) {
                    ElMessage.success("注册成功");
                    // 跳转到登录页面
                    formType.value = 0;
                }
            })
        } else {
            // 登录
            login(loginForm).then(({ data }) => {
                if (data.code === 10000) {
                    ElMessage.success("登录成功");
                    // token 和用户信息 存入 浏览器
                    localStorage.setItem("pz_token", data.data.token);
                    localStorage.setItem("pz_userInfo", JSON.stringify(data.data.userInfo));
                    menuPermissions().then(({ data }) => {
                        // 菜单权限
                        store.commit('dynamicMenu',data.data)
                        // 将响应式数据转为普通的数据 处理
                        toRaw(routerList.value).forEach((item) => {
                            router.addRoute('main',item);
                        })
                        // 跳转到首页
                        router.push({ path: "/" });
                        //console.log(routerList, "登录成功");
                    });


                }
            });

        }

    })
}



</script>

<style lang="scss" scoped>
:deep(.el-card__header) {
    padding: 0;
}

.login-bg {
    min-height: 100vh;
    background: url('@/assets/images/pz-bg.jpg') no-repeat;
    background-size: cover;
    overflow: hidden;
}

.login-container {
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .card-header {
        background-color: #899fe1;

        img {
            width: 430px;
        }
    }

    .jump-link {
        text-align: right;
        margin-bottom: 10px;
    }

    .el-input__suffix-inner {
        cursor: pointer;
    }
}
</style>
